import { createRouter, createWebHistory } from 'vue-router';
import { staticRoutes } from './routes'
import NProgress from "nprogress";
import "nprogress/nprogress.css";
NProgress.configure({ showSpinner: false });
import {
  getCustomLocalStorage,
} from '@/utils/localStorage';

// 引入在axios暴露出的clearPending函数
import { clearPending } from "@/utils/request/index";

// 设置title
import getPageTitle from "@/utils/getPageTitle";

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: staticRoutes,
})

router.beforeEach((to, from, next) => {
  // 设置title
  document.title = getPageTitle(to.meta.title);
  // 开启进度条
  NProgress.start();
  // 在跳转路由之前，先清除所有的请求
  clearPending();
  let whiteArr = ['/forgot'];
  if (whiteArr.includes(to.path)) {
    next();
  } else {
    if (getCustomLocalStorage('token')) {
      if (to.path === '/login') {
        next({ path: '/' });
      } else {
        next();
      }
    } else {
      if (to.path === '/login') {
        next();
      } else {
        next({ path: '/login' });
      }
    }
  }
})

router.afterEach(() => {
  // 完成进度条
  NProgress.done();

});
export default router
